package cn.cs.yangtai.service.impl;

import cn.cs.yangtai.entity.Comminicate;
import cn.cs.yangtai.entity.Commodity;
import cn.cs.yangtai.entity.vo.CommodityVo;
import cn.cs.yangtai.entity.vo.PageResult;
import cn.cs.yangtai.mapper.CommodityMapper;
import cn.cs.yangtai.service.CommodityService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;
import java.util.List;

import javax.annotation.Resource;

/**
 * 商品表(Commodity)表服务实现类
 *
 * @author makejava
 * @since 2024-12-17 13:50:54
 */
@Service("commodityService")
public class CommodityServiceImpl implements CommodityService {
    @Resource
    private CommodityMapper commodityMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param cId 主键
     * @return 实例对象
     */
    @Override
    public CommodityVo queryById(Integer cId) {
        return this.commodityMapper.queryById(cId);
    }

    @Override
    public List<CommodityVo> findTop10BySales() {
        return commodityMapper.selectTop10BySales();
    }

    @Override
    public List<CommodityVo> findRecentCommodities() {
        return commodityMapper.selectRecentCommodities();
    }
    /**
     * 分页查询
     *
     * @param cuttentPage 本页
     * @param pageSize    分页大小
     * @return 查询结果
     */
    @Override
    public PageResult<CommodityVo> queryByPage(Integer cuttentPage, Integer pageSize) {
        PageHelper.startPage(cuttentPage,pageSize);
        Page<CommodityVo> commodities =commodityMapper.queryAllByLimit(new Page<>());
        return PageResult.restPage(commodities);
    }


    @Override
    public boolean isCommodityNameExists(String name) {
        return commodityMapper.selectByName(name) != null;
    }

    @Override
    public Commodity insert(Commodity commodity) {
        if (isCommodityNameExists(commodity.getCName())) {
            // 如果商品名称已存在，抛出异常或者返回错误信息
            throw new RuntimeException("商品已存在");
        }
        commodityMapper.insert(commodity);
        return commodity;
    }
    /**
     * 修改数据
     *
     * @param commodity 实例对象
     * @return 实例对象
     */
    @Override
    public Commodity update(Commodity commodity) {
        this.commodityMapper.update(commodity);
       return commodity;
    }

    /**
     * 通过主键删除数据
     *
     * @param cId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer cId) {
        return this.commodityMapper.deleteById(cId) > 0;
    }
}
